#!/usr/bin/env python
#-*-coding:utf-8-*-
#计算文件中预装渠道的imei数量
import sys
import os
import re
if len(sys.argv) != 3:
    print "argv's length is not 3"
    sys.exit()
#包含渠道信息的文件
channel_info_file_path = sys.argv[1]
#需要识别的文件夹
analysis_file_path = sys.argv[2]

if not os.path.exists(channel_info_file_path):
    print 'file: %s does not exist' % channel_info_file_path
    sys.exit()
elif not os.path.exists(analysis_file_path):
    print 'file: %s does not exist' % analysis_file_path
    sys.exit()
else:
    channel_info_file = open(channel_info_file_path)
    #将channel及渠道信息存入map
    map_k_channel_v_info = {}
    for line in channel_info_file:
        infos = line.rstrip().lstrip().split("\t")
        map_k_channel_v_info[infos[0]] = infos[1]
    channel_info_file.close()
    map_k_channei_info_v_value = {}
    active_user_pattern = "\w+_use_in_\w+\.result"
    active_user_re = re.compile(active_user_pattern)
    run_off_user_pattern = "\w+_not_use\.result"    
    run_off_user_re = re.compile(run_off_user_pattern)
    result_file_pattern = "\w+\.result"    
    result_file_re = re.compile(result_file_pattern)
    for fatherroot, fatherdirs, fatherfiles in os.walk(analysis_file_path):
        for fatherfile in fatherfiles:
            eachFile = os.path.join(analysis_file_path,fatherfile)
            #print eachFile
            result_file_m = result_file_re.match(fatherfile)
            if result_file_m is None:
                continue
            analysis_file = open(eachFile)
            file_pattern_name = ""
            if active_user_re.match(fatherfile) is not None:
                file_pattern_name = "唤醒用户"
            elif run_off_user_re.match(fatherfile) is not None:
                file_pattern_name = "流失用户"
            else:
                file_pattern_name = "沉睡用户"
            for line in analysis_file:
                infos = line.rstrip().lstrip().split("\t")
                if len(infos) < 3:
                    #print "error line :",line
                    continue
                channel_name = infos[2]
                
                if map_k_channel_v_info.has_key(channel_name):
                    channel_info = map_k_channel_v_info[channel_name]
                    if map_k_channei_info_v_value.has_key(file_pattern_name+"\t"+channel_info):
                        map_k_channei_info_v_value[file_pattern_name+"\t"+channel_info] += 1
                    else:
                        map_k_channei_info_v_value[file_pattern_name+"\t"+channel_info] = 1
                else:
                    #print "error channel :",channel_name
                    pass
            analysis_file.close()            
    for key in map_k_channei_info_v_value.keys():
        print key+"\t"+str(map_k_channei_info_v_value[key])
        